<?php


namespace App\Services;


use App\CodeResponse;
use App\Exceptions\BusinessException;
use App\Models\User;
use App\Notifications\VerificationCode;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Notification;
use Leonis\Notifications\EasySms\Channels\EasySmsChannel;
use Overtrue\EasySms\PhoneNumber;

class UserServices extends BaseServices
{
    /**
     * 根据用户名获取用户
     * @param $username
     * @return User|null|object
     */
    public function getByUsernane($username){
        return User::query()->where('username',$username)->where('deleted',0)->first();
    }

    /**
     * 根据手机号获取用户
     * @param $mobile
     * @return User|null|object
     */
    public function getByMobile($mobile){
        return User::query()->where('mobile',$mobile)->where('deleted',0)->first();
    }

    /**
     * 验证手机号码发送验证码是否已经达到限制条数
     * @param string $mobile
     * @return bool
     */
    public function checkMobileSendCaptchaCount(string $mobile){
        $countKey = 'register_captcha_count_'.$mobile;
        if(Cache::has($countKey)){
            $count = Cache::increment($countKey);
            if($count>10){
                return false;
            }
        }else{
            Cache::put($countKey,1,Carbon::tomorrow()->diffInSeconds(now()));
        }
        return true;
    }

    public function sendCaptchaMsg($mobile,$code){
        if(app()->environment('testing')){
            return;
        }
        Notification::route(
            EasySmsChannel::class,
            new PhoneNumber($mobile,86)
        )->notify(new VerificationCode($code));
    }

    /**
     * 验证验证码是否正确
     * @param string $mobile
     * @param string $code
     * @throws BusinessException
     */
    public function checkCaptcha(string $mobile,string $code){
        $key = 'register_captcha_'.$mobile;
        $isPass = $code === Cache::get($key);
        if($isPass){
            Cache::forget($key);
        }else{
            throw new BusinessException(CodeResponse::AUTH_CAPTCHA_UNMATCH);
        }
    }

    /**
     * 随机生成验证码 并 保存手机号和验证码的关系
     * @param string $mobile
     * @param string $code
     * @throws \Exception
     */
    public function setCaptcha(string $mobile){
        $code = strval(random_int(100000,999999));
        Cache::put('register_captcha_'.$mobile,$code,600);
        return $code;
    }
}
